<?php

/**
 * uniBoard User CP
 *
 * Light and fast forum solution for web 2.0-like communities.
 *
 * @package		uniBoard
 * @author		Rafał Pitoń
 * @license		http://www.gnu.org/licenses/gpl-3.0.html
 * @since		Version 0.1
 * 
 * ------------------------------------------------------------------------
 * 
 * $Date: 2010-09-20 21:23:27 +0000 (Mon, 20 Sep 2010) $
 * $Revision: 64 $
 * $Author: rafio.xudb@gmail.com $
 */

// ------------------------------------------------------------------------

class action_user_cp{
	
	/**
	 * Main class pointer
	 *
	 * @var object
	 */
	
	private $appCore		= NULL;
	
	/**
	 * Our Templates
	 *
	 * @var object
	 */
	
	private $templates		= NULL;
	
	/**
	 * Our User API
	 *
	 * @var object
	 */
	
	private $api			= NULL;
	
	// ------------------------------------------------------------------------

	/**
	 * Initialise Action
	 *
	 * @param object $appCore
	 */
	
	function __construct( $appCore){
		
		// Store appCore pointer
		$this -> appCore = $appCore;
		
		// Load Language File
		$appCore -> loadLanguageFile( 'users');
				
		// User Not Logged In?
		if ( $appCore -> user['id'] < 1)
		{
			// Set Event
			$appCore -> output -> setEvent( $appCore -> lang['action_not_allowed_guest'], $appCore -> lang['board_nav_user_cp'], 0);
			
			// Run Events
			$appCore -> output -> drawEvents();
		}
		else
		{						
			// Load Templates
			$this -> templates = new tpl_user_cp( $appCore);
						
			// Start API
			$this -> api = new api_user( $appCore, $appCore -> user['id']);
			
			// Select user action
			switch ( $appCore -> _REQ('do'))
			{
				// Details page
				case 'details':					
					// Draw Form
					$this -> pageDetails();
				break;
				
				// Name Change Page
				case 'name':					
					// Draw Form
					$this -> pageName();
				break;
				
				// Avatar Change Page
				case 'avatar':					
					// Draw Form
					$this -> pageAvatar();
				break;
				
				// Avatars Gallery Page
				case 'gallery':					
					// Draw Form
					$this -> pageGallery();
				break;
				
				// Signature Page
				case 'signature':					
					// Draw Form
					$this -> pageSignature();
				break;
				
				// Change E-Mail Page
				case 'email':					
					// Draw Form
					$this -> pageEmail();
				break;
				
				// Change Password Page
				case 'password':					
					// Draw Form
					$this -> pagePassword();
				break;
				
				// Settings Page
				case 'settings':					
					// Draw Form
					$this -> pageSettings();
				break;
				
				// Default page
				default:
					$this -> pageIndex();
				break;
			}
			
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * User CP index page
	 *
	 */
	
	function pageIndex(){
		
		// Set TPL Vars
		$tpl_vars = array(
			'user_join_date' => $this -> api -> user_join_date,
			'user_posts' => $this -> api -> user_posts
		);
		
		// Select user groups
		$user_groups = $this -> appCore -> users -> getUserGroups( true);
		
		// Reiterate
		foreach ( $user_groups as $group_id => $group_name)
		{
			// Main Group
			if ( $group_id == $this -> api -> group_id)
			{
				$tpl_vars['user_group_name'] = $group_name;
			}
		}
		
		// Draw
		$this -> draw($this -> templates -> tpl_user_cp_home($tpl_vars), 'index');
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * User CP Details page
	 *
	 */
	
	function pageDetails(){
		
		// Update?
		if ( $this -> appCore -> _POST('update') == 1)
		{
			// Field checks out?
			if ( $this -> appCore -> validRequest())
			{
				// Set Custom title?
				if ( $this -> appCore -> conf['user_custom_title_lenght'] > 0)
				{
					$this -> api -> setUserTitle( $this -> appCore -> _POST( 'custom_title'));
				}
				
				// Any errors?
				if ( $this -> api -> error)
				{
					// All cool
					$this -> appCore -> output -> setEvent( join( '<br/>', $this -> api -> errors), $this -> appCore -> lang['user_cp_details'], 0);			
				}
				else
				{
					// Save api
					$this -> api -> saveData();
					
					// Update user array, set new title
					if ( $this -> appCore -> conf['user_custom_title_lenght'] > 0)
					{
						$this -> appCore -> user['title'] = $this -> api -> user_title;
					}
					
					// All cool
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_details_changed'], $this -> appCore -> lang['user_cp_details'], 1);			
				}
			}
			else
			{
				// Show error
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
			}
		}
		
		// Set TPL Vars
		$tpl_vars = array(
			'act_code' => $this -> appCore -> session -> session_code,
			'act_key' => $this -> appCore -> session -> session_key
		);
		
		// Show Custom title?
		if ( $this -> appCore -> conf['user_custom_title_lenght'] > 0)
		{
			// Show custom title
			$tpl_vars['display_custom_title'] = 1;
			
			// Field content
			$tpl_vars['custom_title'] = $this -> api -> user_title;
		}
		
		// Draw
		$this -> draw($this -> templates -> tpl_user_cp_details($tpl_vars), 'details');
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * User CP Name page
	 *
	 */
	
	function pageName(){
		
		// Allow names change?
		if ( !$this -> appCore -> conf['users_allow_name_change'])
		{
			// Option off
			$this -> appCore -> output -> setEvent( $this -> appCore -> lang['action_not_allowed_disabled'], $this -> appCore -> lang['user_cp_name'], 0);			
			
			// Draw index page
			$this -> pageIndex();	
		}
		else
		{
			// Update?
			if ( $this -> appCore -> _POST('update') == 1)
			{
				// Field checks out?
				if ( $this -> appCore -> validRequest())
				{
					// Timeout?
					if ( $this -> appCore -> conf['users_name_change_span'] > 0 && $this -> api -> user_name_date + ($this -> appCore -> conf['users_name_change_span'] * 86400) > $this -> appCore -> time)
					{
						// Too fast, count days needed to wait
						$days_left = floor((($this -> api -> user_name_date + ($this -> appCore -> conf['users_name_change_span'] * 86400)) - $this -> appCore -> time) / 86400);
						
						// Draw Message
						$this -> api -> setError( $days_left == 0 ? $this -> appCore -> lang['api_user_name_too_fast'] : sprintf( $this -> appCore -> lang['api_user_name_too_fast_plural'], $days_left));			
					}
					else
					{
						// Password Valid?
						if ( $this -> appCore -> hashPassword($this -> appCore -> _POST('user_password'), $this -> api -> user_salt) != $this -> api -> user_password)
						{
							// Incorrect password
							$this -> api -> setError( $this -> appCore -> lang['user_cp_wrong_pass']);
						}
						
						// New name empty
						if ( strlen( $this -> appCore -> _POST('new_user_name')) > 0)
						{
							// Same?
							if ( $this -> appCore -> _POST('new_user_name') != $this -> api -> user_name)
							{
								// Put it to api
								$this -> api -> setUserName( $this -> appCore -> _POST('new_user_name'));
							}
							else
							{
								// Same name
								$this -> api -> setError( $this -> appCore -> lang['user_cp_new_name_same']);
							}
						}
						else
						{
							// Empty name
							$this -> api -> setError( $this -> appCore -> lang['user_cp_new_name_empty']);
						}
					}
					
					// Any errors?
					if ( $this -> api -> error)
					{
						// All cool
						$this -> appCore -> output -> setEvent( join( '<br/>', $this -> api -> errors), $this -> appCore -> lang['user_cp_name'], 0);			
					}
					else
					{
						// Set Name Data
						$this -> api -> setUserNameDate($this -> appCore -> time);
						
						// Save api
						$this -> api -> saveData();
						
						// Update Name
						$this -> appCore -> users -> updateUserName( $this -> api -> user_id, $this -> api -> user_name);
						
						// All cool, redirect user to form
						$this -> appCore -> output -> drawRedirect( $this -> appCore -> niceLink('act=user_cp&do=name',$this -> appCore -> lang['user_cp_name']), $this -> appCore -> lang['user_cp_name_changed']);			
						
						// Kill action
						return;
					}
				}
				else
				{
					// Show error
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
				}
			}
			
			// Set TPL Vars
			$tpl_vars = array(
				'act_code' 				=> $this -> appCore -> session -> session_code,
				'act_key' 				=> $this -> appCore -> session -> session_key,
				'current_user_name' 	=> htmlspecialchars( $this -> api -> user_name),
				'user_name_date' 		=> $this -> api -> user_name_date,
			);
			
			// Draw
			$this -> draw($this -> templates -> tpl_user_cp_name($tpl_vars), 'details');
		}
			
	}
	
	// ------------------------------------------------------------------------

	/**
	 * User CP Avatar Page
	 *
	 */
	
	function pageAvatar(){
		
		// Set New Avatar?
		if ( $this -> appCore -> _POST('set_new') == 1 && ($this -> appCore -> conf['avatars_allow_remote'] || $this -> appCore -> conf['avatars_allow_upload']))
		{
			// Valid Request
			if ( $this -> appCore -> validRequest())
			{
				// Grab use file types
				$file_types = $this -> getAvatarTypes();
				
				// Get default avatar size
				$avatar_size_max = $this -> getAvatarSizes();
								
				// Check remote avatar?
				if ( $this -> appCore -> conf['avatars_allow_remote'] && strlen($this -> appCore -> _POST('remote_avatar')) > 0)
				{
					// Grab file
					$new_avatar = $this -> appCore -> fixLink( $this -> appCore -> _POST('remote_avatar'));
					
					// File Type?
					if (strpos( $new_avatar, '.') !== false && in_array( strtolower( substr( $new_avatar, strrpos( $new_avatar, '.'))), $file_types))
					{
						// Define avatar size
						@$avatar_size = getimagesize( $new_avatar);
						
						// Not found, set default?
						if ( $avatar_size == false)
						{
							$avatar_size = $avatar_size_max;
						}
						
						// Fix Max dimensions
						$avatar_size = $this -> appCore -> scaleImage($avatar_size[0], $avatar_size[1], $avatar_size_max[0], $avatar_size_max[1]);
						
						// Delete current avatar
						$this -> api -> deleteUserAvatar();
						
						// Set new avatar
						$this -> api -> setUserAvatarType( 1);
						$this -> api -> setUserAvatarImage( $new_avatar);
						$this -> api -> setUserAvatarWidth( $avatar_size[0]);
						$this -> api -> setUserAvatarHeight( $avatar_size[1]);
						
						// Save API
						$this -> api -> saveData();
						
						// Redirect us back
						$this -> appCore -> output -> drawRedirect( $this -> appCore -> niceLink('act=user_cp&do=avatar',$this -> appCore -> lang['user_cp_avatar']), $this -> appCore -> lang['user_cp_avatar_set']);			
						
						// Kill action
						return;
					}
					else
					{
						// Nothing sent
						$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_avatar_type_incorrect'], $this -> appCore -> lang['user_cp_avatar'], 0);
					}
				}
				else if ( $this -> appCore -> conf['avatars_allow_upload'])
				{
					// Make upload object
					$file_upload = new api_file_upload( $this -> appCore, 'upload_avatar');
					
					// Configure it
					$file_upload -> setUploadSize( $this -> appCore -> conf['avatars_upload_size']);
					$file_upload -> setExtensions( $file_types);
					
					// Catch upload
					$file_upload -> catchFile();
					
					// Error?
					if ( $file_upload -> error)
					{
						// Api gived us errros
						$this -> appCore -> output -> setEvent( join('<br/>', $file_upload -> errors), $this -> appCore -> lang['user_cp_avatar'], 0);
					}
					else
					{
						// Move new file to uploads
						$file_upload -> moveFile( UPLOADS_PATH, 'avatar_' . $this -> api -> user_id . $file_upload -> getFileExtension());
						
						// Define avatar size
						@$avatar_size = getimagesize( UPLOADS_PATH . 'avatar_' . $this -> api -> user_id . $file_upload -> getFileExtension());
						
						// Not found, set default?
						if ( $avatar_size == false)
						{
							$avatar_size = $avatar_size_max;
						}
						
						// Fix Max dimensions
						$avatar_size = $this -> appCore -> scaleImage($avatar_size[0], $avatar_size[1], $avatar_size_max[0], $avatar_size_max[1]);
												
						// Delete current avatar
						$this -> api -> deleteUserAvatar();
						
						// Set new avatar
						$this -> api -> setUserAvatarType( 3);
						$this -> api -> setUserAvatarImage( 'avatar_' . $this -> api -> user_id . $file_upload -> getFileExtension());
						$this -> api -> setUserAvatarWidth( $avatar_size[0]);
						$this -> api -> setUserAvatarHeight( $avatar_size[1]);
						
						// Save API
						$this -> api -> saveData();
						
						// Redirect us back
						$this -> appCore -> output -> drawRedirect( $this -> appCore -> niceLink('act=user_cp&do=avatar',$this -> appCore -> lang['user_cp_avatar']), $this -> appCore -> lang['user_cp_avatar_set']);			
						
						// Kill action
						return;
					}
				}
				else
				{
					// Nothing sent
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_avatars_none'], $this -> appCore -> lang['user_cp_avatar'], 0);
				}
			}
			else
			{
				// Show error
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
			}
		}
		
		// Change exsisting avatar?
		if ($this -> api -> user_avatar_type > 0 && $this -> appCore -> _POST('edit') == 1)
		{
			// Valid Request
			if ( $this -> appCore -> validRequest())
			{
				// Nail our avatar?
				if ( strlen($this -> appCore -> _POST('delete')) > 0)
				{
					// Api gives us easy way to pwn avatar
					$this -> api -> deleteUserAvatar();
					
					// Save Api
					$this -> api -> saveData();
					
					// Draw Message
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_avatar_deleted'], $this -> appCore -> lang['user_cp_avatar'], 1);
				}
				else
				{
					// Get default avatar size
					$avatar_size_max = $this -> getAvatarSizes();
					
					// Get new dimensions
					$avatar_size = array(
						(integer) $this -> appCore -> _POST('avatar_width'),
						(integer) $this -> appCore -> _POST('avatar_height')
					);
					
					// Fix em
					$avatar_size = $this -> appCore -> scaleImage($avatar_size[0], $avatar_size[1], $avatar_size_max[0], $avatar_size_max[1]);
					
					// Save API
					$this -> api -> setUserAvatarWidth( $avatar_size[0]);
					$this -> api -> setUserAvatarHeight( $avatar_size[1]);
					
					// Save API
					$this -> api -> saveData();
							
					// Draw Message
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_avatar_edited'], $this -> appCore -> lang['user_cp_avatar'], 1);
				}
			}
			else
			{
				// Show error
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
			}
		}
		
		// Set TPL Vars
		$tpl_vars = array(
			'act_code' 					=> $this -> appCore -> session -> session_code,
			'act_key' 					=> $this -> appCore -> session -> session_key,
			'avatar_type' 				=> $this -> api -> user_avatar_type,
			'avatar_image'				=> class_users::avatarLocation($this -> api -> user_avatar_type) . $this -> api -> user_avatar_image,
			'avatar_image_raw'			=> $this -> api -> user_avatar_image,
			'avatar_width' 				=> $this -> api -> user_avatar_width,
			'avatar_height' 			=> $this -> api -> user_avatar_height,
			'avatars_allow_remote'		=> $this -> appCore -> conf['avatars_allow_remote'],
			'avatars_allow_upload'		=> $this -> appCore -> conf['avatars_allow_upload'],
			'max_upload_size'			=> $this -> appCore -> conf['avatars_upload_size'],
			'avatars_allow_gallery'		=> $this -> appCore -> conf['avatars_allow_gallery'] && USE_GLOB
		);
		
		// Draw
		$this -> draw($this -> templates -> tpl_user_cp_avatar($tpl_vars), 'avatar');
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Draws Avatars gallery page
	 *
	 */
	
	function pageGallery(){
		
		// Allow gallery?
		if ($this -> appCore -> conf['avatars_allow_gallery'] && USE_GLOB)
		{
			// Set?
			if ( strlen($this -> appCore -> _GET('set')) > 0)
			{
				// Valid Request
				if ( $this -> appCore -> validRequest(false))
				{
					// Grab use file types
					$file_types = $this -> getAvatarTypes();
					
					// Get default avatar size
					$avatar_size_max = $this -> getAvatarSizes();
									
					// Grab new file
					$new_file = str_replace( array('../', '..\\', '/', '\\'), '', $this -> appCore -> _GET('set'));
					
					// Grab extension
					$new_file_extension = substr($new_file, strrpos($new_file, '.'));
					
					// Try-catch
					try
					{
						// Extension incorrect
						if ( !in_array( $new_file_extension, $file_types))
						{
							throw new exc_small($this -> appCore -> lang['user_cp_avatar_type_incorrect']);
						}
						
						// File exists?
						if (!file_exists(AVATARS_GALLERY_PATH . $new_file))
						{
							throw new exc_small($this -> appCore -> lang['user_cp_avatars_none']);
						}
						
						// Define avatar size
						@$avatar_size = getimagesize( AVATARS_GALLERY_PATH . $new_file);
						
						// Not found, set default?
						if ( $avatar_size == false)
						{
							$avatar_size = $avatar_size_max;
						}
						
						// Fix Max dimensions
						$avatar_size = $this -> appCore -> scaleImage($avatar_size[0], $avatar_size[1], $avatar_size_max[0], $avatar_size_max[1]);
												
						// Delete current avatar
						$this -> api -> deleteUserAvatar();
						
						// Set new avatar
						$this -> api -> setUserAvatarType( 2);
						$this -> api -> setUserAvatarImage( $new_file);
						$this -> api -> setUserAvatarWidth( $avatar_size[0]);
						$this -> api -> setUserAvatarHeight( $avatar_size[1]);
						
						// Save API
						$this -> api -> saveData();
						
						// Redirect us back
						$this -> appCore -> output -> drawRedirect( $this -> appCore -> niceLink('act=user_cp&do=avatar',$this -> appCore -> lang['user_cp_avatar']), $this -> appCore -> lang['user_cp_avatar_set']);			
						
						// Kill action
						return;
					}
					catch (exc_small $exception)
					{
						// Show error
						$this -> appCore -> output -> setEvent( $exception -> message, $this -> appCore -> lang['user_cp_avatars_gallery'], 0);
					}
				}
				else
				{
					// Show error
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
				}
			}
			
			// Template variables
			$tpl_vars = array('gallery_avatars' => '');
			
			// Grab teh imagezz
			$image_files = glob( AVATARS_GALLERY_PATH . '*.{gif,jpeg,jpg,png}', GLOB_BRACE);
			
			// Number of images
			$images_n = count($image_files);
			
			// Reiterate?
			if ( $images_n > 0)
			{
				for ($i = 0; $i < $images_n; $i++)
				{
					// Draw Image
					$tpl_vars['gallery_avatars'] .= $this -> templates -> tpl_user_cp_avatar_gallery_item( array(
						'avatar_set_url'	=> $this -> appCore -> niceLink('act=user_cp&do=gallery&set=' . urlencode(substr($image_files[$i], strrpos( $image_files[$i], '/') + 1)).'&' . $this -> appCore -> session -> session_key . '=' . $this -> appCore -> session -> session_code, substr($image_files[$i], strrpos( $image_files[$i], '/') + 1)),
						'avatar_src_url'	=> $image_files[$i],
						'avatar_image'		=> htmlspecialchars(substr($image_files[$i], strrpos( $image_files[$i], '/') + 1))
					));
				}
			}
			
			// Draw
			$this -> draw($this -> templates -> tpl_user_cp_avatar_gallery($tpl_vars), 'avatar');
		}
		else
		{
			// Nope, too bad
			$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_avatar_gallery_not_avaiable'], $this -> appCore -> lang['user_cp_avatars_gallery'], 0);
			
			// Draw Avatar Page
			$this -> pageAvatar();
		}
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Returns allowed avatar types
	 * 
	 * @return array
	 */
	
	function getAvatarTypes(){
		
		// Grab use file types
		$file_types = explode( ',', $this -> appCore -> conf['avatars_types']);
		
		// Reiterate
		foreach ( $file_types as $type_id => $type_name)
		{
			// Trim name
			$type_name = strtolower( trim( $type_name));
			
			// Not Empty?
			if ( isset($type_name[0]) && stripos( $type_name, 'php') === false)
			{
				// Update it
				$file_types[$type_id] = '.' . $type_name;
			}
			else
			{
				// Kill it
				unset($file_types[$type_id]);
			}
		}
		
		// Empty?
		if ( empty($file_types))
		{
			// Set at least gif extension
			$file_types[] = '.gif';
		}

		// Return ready types
		return $file_types;
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Returns allowed avatar sizes
	 * 
	 * @return array
	 */
	
	function getAvatarSizes(){
		
		// Get default avatar size
		$avatar_size_max = explode('x', $this -> appCore -> conf['avatars_dimensions_size']);
		
		// Size incorrect?
		if ( count( $avatar_size_max) != 2)
		{
			// Set defautly 100 x 100
			$avatar_size_max = array( 100, 100);
		}
		else
		{
			// Force integers
			settype( $avatar_size_max[0], 'integer');
			settype( $avatar_size_max[1], 'integer');
			
			// Fix zeros
			if ( $avatar_size_max[0] < 1)
			{
				$avatar_size_max[0] = 100;
			}
			
			if ( $avatar_size_max[1] < 1)
			{
				$avatar_size_max[1] = 100;
			}
		}
		
		// Return ready size
		return $avatar_size_max;
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Signature edit page
	 *
	 */
	
	function pageSignature(){
		
		// Allow sigs?
		if ( $this -> appCore -> conf['signatures_allow'])
		{	
			// Set Signature
			if ( $this -> appCore -> _POST('update'))
			{
				// Valid Request
				if ( $this -> appCore -> validRequest())
				{
					// Make Parser
					$parser = new class_parser($this -> appCore, false);
					
					// Set Api
					$this -> api -> setUserSignatureRaw($this -> appCore -> _POST('user_signature'));
					$parsed_signature = $parser -> preparse($this -> appCore -> _POST('user_signature'), array(
						'bbcode' 	=> $this -> appCore -> conf['signatures_bbcodes'] && $this -> appCore -> getByte('user_signature_op_bbcodes'),
						'smileys' 	=> $this -> appCore -> conf['signatures_smileys'] && $this -> appCore -> getByte('user_signature_op_smileys'),
						'urls' 		=> $this -> appCore -> conf['signatures_links'],
						'links' 	=> $this -> appCore -> conf['signatures_links'] && $this -> appCore -> getByte('user_signature_op_links'),
						'geshi' 	=> $this -> appCore -> conf['signatures_geshi'],
						'images'	=> $this -> appCore -> conf['signatures_images'],
						'youtube' 	=> 0
					));
					
					// Geshi Limit
					if ( $this -> appCore -> conf['signatures_geshi_limit']  > 0 && $parser -> text_geshi > $this -> appCore -> conf['signatures_geshi_limit'])
					{
						// Set Error
						$this -> api -> setError(sprintf($this -> appCore -> lang['user_cp_signature_geshi_limit'], $this -> appCore -> conf['signatures_geshi_limit']));
					}
					
					// Images Limit
					if ( $this -> appCore -> conf['signatures_images_limit']  > 0 && $parser -> text_images > $this -> appCore -> conf['signatures_images_limit'])
					{
						// Set Error
						$this -> api -> setError(sprintf($this -> appCore -> lang['user_cp_signature_images_limit'], $this -> appCore -> conf['signatures_images_limit']));
					}
					
					// Links Limit
					if ( $this -> appCore -> conf['signatures_links_limit']  > 0 && $parser -> text_links > $this -> appCore -> conf['signatures_links_limit'])
					{
						// Set Error
						$this -> api -> setError(sprintf($this -> appCore -> lang['user_cp_signature_links_limit'], $this -> appCore -> conf['signatures_links_limit']));
					}
					
					// Smileys Limit
					if ( $this -> appCore -> conf['signatures_smileys_limit']  > 0 && $parser -> text_smileys > $this -> appCore -> conf['signatures_smileys_limit'])
					{
						// Set Error
						$this -> api -> setError(sprintf($this -> appCore -> lang['user_cp_signature_smileys_limit'], $this -> appCore -> conf['signatures_smileys_limit']));
					}
									
					// Kill Parser
					unset($parser);
										
					// Stuff checks?
					if ( $this -> api -> error)
					{	
						// Show error
						$this -> appCore -> output -> setEvent( join('<br/>', $this -> api -> errors), $this -> appCore -> lang['user_cp_signature'], 0);
					}
					else
					{
						// Set Api
						$this -> api -> setUserSignature( $parsed_signature);
						
						// Set Configuration
						$this -> api -> setUserSignatureSet(($this -> appCore -> conf['signatures_bbcodes'] ? $this -> appCore -> getByte('user_signature_op_bbcodes') : 1).($this -> appCore -> conf['signatures_smileys'] ? $this -> appCore -> getByte('user_signature_op_smileys') : 1).($this -> appCore -> conf['signatures_links'] ? $this -> appCore -> getByte('user_signature_op_links') : 1));
						
						// Save Api
						$this -> api -> saveData();
						
						// Show message
						$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_signature_changed'], $this -> appCore -> lang['user_cp_signature'], 1);
					}
				}
				else
				{
					// Show error
					$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
				}
			}
			
			// Template Vars
			$tpl_vars = array(
				'act_code'		=> $this -> appCore -> session -> session_code,
				'act_key'		=> $this -> appCore -> session -> session_key
			);
			
			// Parse user Signature?
			if ( isset($this -> api -> user_signature[0]))
			{
				// Start parser
				$parser = new class_parser($this -> appCore, true);
				
				// Parse signature
				$tpl_vars['parsed_signature'] = $parser -> finalise($this -> api -> user_signature);
				
				// Kill Parser
				unset($parser);
			}
			
			// Start editor
			$editor = new class_editor($this -> appCore, 'user_signature', $this -> api -> user_signature_raw);
			
			// Set config
			$editor -> setConfig(array(
				'bbcode' 	=> $this -> appCore -> conf['signatures_bbcodes'],
				'smileys' 	=> $this -> appCore -> conf['signatures_smileys'],
				'links' 	=> $this -> appCore -> conf['signatures_links'],
				'geshi' 	=> $this -> appCore -> conf['signatures_geshi'],
				'images'	=> $this -> appCore -> conf['signatures_images'],
				'youtube' 	=> 0
			));
			
			// Draw It
			$tpl_vars['signature_editor'] = $editor -> draw(false);
			
			// Build signature options
			$signature_options = array();
			
			// BBcodes?
			if ( $this -> appCore -> conf['signatures_bbcodes'])
			{
				// Parse Codes
				$signature_options[] = 'bbcodes';
				
				// Parse links
				if ( $this -> appCore -> conf['signatures_links'])
				{
					$signature_options[] = 'links';
				}
			}
			
			// Parse smileys
			if ( $this -> appCore -> conf['signatures_smileys'])
			{
				$signature_options[] = 'smileys';
			}
			
			// Draw Options
			$tpl_vars['signature_options'] = $editor -> drawOptions(array(
				'bbcodes', 'smileys', 'links'
			), array(
				'bbcodes'	=> $this -> appCore -> conf['signatures_bbcodes'] && (isset($this -> api -> user_signature_set[0]) ? $this -> api -> user_signature_set[0] : 1),
				'smileys'	=> $this -> appCore -> conf['signatures_smileys'] && (isset($this -> api -> user_signature_set[1]) ? $this -> api -> user_signature_set[1] : 1),
				'links' 	=> $this -> appCore -> conf['signatures_bbcodes'] && $this -> appCore -> conf['signatures_links'] && (isset($this -> api -> user_signature_set[2]) ? $this -> api -> user_signature_set[2] : 1)
			));
			
			// Draw
			$this -> draw($this -> templates -> tpl_user_cp_signature($tpl_vars), 'signature');
		}
		else
		{
			// Set Error
			$this -> appCore -> output -> setEvent( $this -> appCore -> lang['action_not_allowed_disabled'], $this -> appCore -> lang['user_cp_signature'], 0);
			
			// Show CP index
			$this -> pageIndex();
		}
	}
	
	// ------------------------------------------------------------------------

	/**
	 * E-Mail Change Page
	 *
	 */
	
	function pageEmail(){
		
		// Change E-Mail
		if ( $this -> appCore -> _POST('update'))
		{
			// Valid Request
			if ( $this -> appCore -> validRequest())
			{
				// Try-catch
				try
				{
					// Pass empty or incorrect?
					if ( strlen($this -> appCore -> _POST('user_password')) == 0 || $this -> appCore -> hashPassword($this -> appCore -> _POST('user_password'), $this -> api -> user_salt) != $this -> api -> user_password)
					{
						throw new exc_small($this -> appCore -> lang['user_cp_wrong_pass']);
					}
					
					// One of fields empty?
					if (strlen($this -> appCore -> _POST('new_user_email')) == 0 || strlen($this -> appCore -> _POST('new_user_email_repeat')) == 0)
					{
						throw new exc_small($this -> appCore -> lang['user_cp_fields_all']);
					}
					
					// Fields differ between each other?
					if ($this -> appCore -> _POST('new_user_email') != $this -> appCore -> _POST('new_user_email_repeat'))
					{
						throw new exc_small($this -> appCore -> lang['user_cp_fields_different']);
					}
					
					// New Mail is same as current mail?
					if ( class_strings::stripLines(mb_strtolower($this -> appCore -> _POST('new_user_email'))) == $this -> api -> user_email)
					{
						throw new exc_small($this -> appCore -> lang['user_cp_new_email_same']);
					}
					
					// Change email
					$this -> api -> setUserEmail($this -> appCore -> _POST('new_user_email'));
					
					// Api errors?
					if ( $this -> api -> error)
					{
						// Show error
						throw new exc_small(join('<br/>', $this -> api -> errors));
					}
					else
					{
						// Save Api
						$this -> api -> saveData();
							
						// Redirect us back
						$this -> appCore -> output -> drawRedirect( $this -> appCore -> niceLink('act=user_cp&do=email',$this -> appCore -> lang['user_cp_change_email']), $this -> appCore -> lang['user_cp_email_changed']);			
						
						// Kill action
						return;
					}
				}
				catch (exc_small $exception)
				{
					// Show error
					$this -> appCore -> output -> setEvent( $exception -> message, $this -> appCore -> lang['user_cp_change_email'], 0);
				}
			}
			else
			{
				// Show error
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
			}
		}
		
		// Template Vars
		$tpl_vars = array(
			'act_code'					=> $this -> appCore -> session -> session_code,
			'act_key'					=> $this -> appCore -> session -> session_key,
			'current_user_email'		=> htmlspecialchars($this -> api -> user_email),
			'new_user_email'			=> $this -> appCore -> _POST('new_user_email'),
			'new_user_email_repeat'		=> $this -> appCore -> _POST('new_user_email_repeat')
		);
		
		// Draw
		$this -> draw($this -> templates -> tpl_user_cp_email($tpl_vars), 'email');
	
	}
	// ------------------------------------------------------------------------

	/**
	 * Password Change Page
	 *
	 */
	
	function pagePassword(){
		
		// Change E-Mail
		if ( $this -> appCore -> _POST('update'))
		{
			// Valid Request
			if ( $this -> appCore -> validRequest())
			{
				// Try-catch
				try
				{
					// Pass empty or incorrect?
					if ( strlen($this -> appCore -> _POST('user_password')) == 0 || $this -> appCore -> hashPassword($this -> appCore -> _POST('user_password'), $this -> api -> user_salt) != $this -> api -> user_password)
					{
						throw new exc_small($this -> appCore -> lang['user_cp_wrong_pass']);
					}
					
					// One of fields empty?
					if (strlen($this -> appCore -> _POST('new_user_password')) == 0 || strlen($this -> appCore -> _POST('new_user_password_repeat')) == 0)
					{
						throw new exc_small($this -> appCore -> lang['user_cp_fields_all']);
					}
					
					// Fields differ between each other?
					if ($this -> appCore -> _POST('new_user_password') != $this -> appCore -> _POST('new_user_password_repeat'))
					{
						throw new exc_small($this -> appCore -> lang['user_cp_fields_different']);
					}
					
					// New Mail is same as current mail?
					if ( $this -> appCore -> hashPassword($this -> appCore -> _POST('new_user_password'), $this -> api -> user_salt) == $this -> api -> user_password)
					{
						throw new exc_small($this -> appCore -> lang['user_cp_new_password_same']);
					}
					
					// Change email
					$this -> api -> setUserPassword($this -> appCore -> _POST('new_user_password'));
					
					// Api errors?
					if ( $this -> api -> error)
					{
						// Show error
						throw new exc_small(join('<br/>', $this -> api -> errors));
					}
					else
					{
						// Save Api
						$this -> api -> saveData();
							
						// Redirect us back
						$this -> appCore -> output -> drawRedirect( $this -> appCore -> niceLink('act=user_cp&do=password',$this -> appCore -> lang['user_cp_change_pass']), $this -> appCore -> lang['user_cp_password_changed']);			
						
						// Kill action
						return;
					}
				}
				catch (exc_small $exception)
				{
					// Show error
					$this -> appCore -> output -> setEvent( $exception -> message, $this -> appCore -> lang['user_cp_change_pass'], 0);
				}
			}
			else
			{
				// Show error
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
			}
		}
		
		// Template Vars
		$tpl_vars = array(
			'act_code'					=> $this -> appCore -> session -> session_code,
			'act_key'					=> $this -> appCore -> session -> session_key,
			'password_date'				=> $this -> api -> user_password_date,
			'new_user_password'			=> $this -> appCore -> _POST('new_user_email'),
			'new_user_email_repeat'		=> $this -> appCore -> _POST('new_user_email_repeat')
		);
		
		// Draw
		$this -> draw($this -> templates -> tpl_user_cp_password($tpl_vars), 'password');
	
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Board Settings Page
	 *
	 */
	
	function pageSettings(){
		
		// Update?
		if ( $this -> appCore -> _POST('update') == 1)
		{
			// Field checks out?
			if ( $this -> appCore -> validRequest())
			{
				// Set Api
				$this -> api -> setUserWantEmails( $this -> appCore -> _POST( 'user_want_emails'));
				$this -> api -> setUserShowEmail( $this -> appCore -> _POST( 'user_show_email'));
				$this -> api -> setUserWantMailings( $this -> appCore -> _POST( 'user_want_mailings'));
				$this -> api -> setUserTimezone( $this -> appCore -> _POST( 'user_timezone'));
				$this -> api -> setUserDST( $this -> appCore -> _POST( 'user_dst'));
				
				// Save api
				$this -> api -> saveData();
				
				// Update clock
				$this -> appCore -> time_zone = $this -> api -> user_timezone * 3600;
				$this -> appCore -> time_dst = $this -> api -> user_dst;
				
				// Draw message
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['user_cp_settings_changed'], $this -> appCore -> lang['user_cp_board_settings'], 1);
			}
			else
			{
				// Show error
				$this -> appCore -> output -> setEvent( $this -> appCore -> lang['wrong_action_auth'], $this -> appCore -> lang['wrong_action_auth_title'], 0);
			}
		}
		
		// Template Vars
		$tpl_vars = array(
			'act_code'		=> $this -> appCore -> session -> session_code,
			'act_key'		=> $this -> appCore -> session -> session_key
		);
		
		// Set Fields
		$tpl_vars['time_now'] = $this -> appCore -> time;
		$tpl_vars['user_want_emails'] = $this -> api -> user_want_emails;
		$tpl_vars['user_show_email'] = $this -> api -> user_show_email;
		$tpl_vars['user_want_mailings'] = $this -> api -> user_want_mailings;
		$tpl_vars['timezones_list'] = $this -> appCore -> drawRawList( $this -> appCore -> getTimezones(), $this -> api -> user_timezone);
		$tpl_vars['user_dst'] = $this -> api -> user_dst;
		
		// Draw
		$this -> draw($this -> templates -> tpl_user_cp_settings($tpl_vars), 'settings');
		
	}
	
	// ------------------------------------------------------------------------

	/**
	 * Our wrapper for displaying User CP body
	 *
	 * @param string $html
	 * @param string $section
	 */
	
	function draw( $content, $section){
		
		// Fill Template
		$this -> appCore -> output -> draw($this -> appCore -> lang['board_nav_user_cp'], array(
			array($this -> appCore -> niceLink('act=user_cp', $this -> appCore -> lang['board_nav_user_cp']), $this -> appCore -> lang['board_nav_user_cp'])
		), $this -> templates -> tpl_user_cp_body(array(
			'section' => $section,
			'content' => $content
		)));
		
	}
}